﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SimpleActor.Test
{
    internal class TestServiceScope
    {
        public static TestServiceScope Create(Action<ITestService> action)
        {
            var ret = new TestServiceScope(action);
            return ret;
        }

        public static TestServiceScope CreateDetail(Action<TestServiceProxy, MessageScheduler<ITestServant>, TestServant> action)
        {
            var ret = new TestServiceScope(action);
            return ret;
        }

        private TestServant servant;
        private MessageScheduler<ITestServant> scheduler;
        private TestServiceProxy proxy;
        private Action run;

        private TestServiceScope(Action<ITestService> action)
        {
            this.run = () => action(this.proxy);

            Run();
        }

        private TestServiceScope(Action<TestServiceProxy, MessageScheduler<ITestServant>, TestServant> action)
        {
            this.run = () => action(this.proxy, this.scheduler, this.servant);

            Run();
        }

        private void Run()
        {
            servant = new TestServant();
            scheduler = new MessageScheduler<ITestServant>("Service", servant);
            proxy = new TestServiceProxy(scheduler);

            proxy.Start().Wait();

            run();

            proxy.Stop().Wait();
        }
    }
}
